﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Xml;
using PrintDrawing.BaseClassDraw;
using System.Data;
using System.Drawing.Printing;
using Print.Graphic_Print.BaseClassDraw;
using Component;
using PrintTemplate.Graphic_Print.BaseClassDraw;

namespace PrintDrawing
{
    /// <summary>
    /// Interaction logic for DrawTextInfo.xaml
    /// </summary>
    public partial class DrawTextInfo : UserControl
    {
        #region Private field & Contrustion

        private enum STATUS { DONE, CREATE, UPDATE };
        private STATUS status = STATUS.DONE;
        private Brush baseBrushText;//BaseBrushText
        System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
        System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
        FontDialog.FontChooser fontdialog;
        SetDataSource sourceDialog;
        Popup popUppage = new Popup();
        Popup popupfont = new Popup(); //pop up cho font_edit
        Popup popupsource = new Popup(); //pop up cho source
        Popup popupsite = new Popup(); //pop up cho 
        ContextMenu mnu = new ContextMenu();//tao me nu cho cac text box
        private static int CANVASCOUNT = 1; // biến đếm canvas tiện cho đặt tên
        private static int TEXTBOXCOUNT = 1; // biến đếm textbox tiện cho đặt tên

        private double widthParent = 0; // chiều rộng của border
        private double heightParent = 0;// Chiều cao của border
        private double leftTextBox = 0; //lề trái gốc của đối tượng textBox
        private double topTextBox = 0;// lề trên gốc của đối tượng textBox
        private double leftImage = 0; //lề trái gốc của đối tượng image
        private double topImage = 0;// lề trên gốc của đối tượng image
        private double leftface = 0; // xác định lề trái của khung nhìn mặc định =0
        private double topface = 0; // xác định lề trên của khung nhìn mặc định =0
        private double left = 0;  //lề trái của đối tượng đồ họa
        private double top = 0; // lề trên của đối tượng đồ họa
        private ScrollViewer borderCurrent = new ScrollViewer(); // vi tri current border
        // private const double MiniToPixel = 0.24558; // tỷ lệ pixel và cm
        private const int HEIGHT_TEXT = 19; // fix cứng chiều cao textBox

        //infor print   
        private PrintInfo printInfo = new PrintInfo();
        string fileName = "";
        //--end infor print

        private TabItem tabItem = new TabItem();  // current tabItem
        private Canvas canvas = new Canvas();      // current canvas   
        private TextBoxDrawn originalText;      // current textBox
        private ImageDrawn origionalImage;
        private Point startPoint = new Point();// giữ điểu đầu
        private Shape rubberBand = null;  // hình vuông nền khi vẽ textBox
        Point currentPoint = new Point(); // giữ vị trí hiện tại
        AdornerLayer myAdornerLayer; // tao nền adorner cho obj

        private bool isDragging = false; // trạng thái kiểm tra đang vẽ
        private bool isMovingText = false;  // trạng thái kiểm tra moving TextBox 
        private bool isMovingImage = false;
        private BaseClassDraw.ConfigPrintLaze _configPrint = new PrintDrawing.BaseClassDraw.ConfigPrintLaze();

        Dictionary<string, string> DicImageBackGround = new Dictionary<string, string>();
        private System.Data.DataTable _tblSource;
        List<TextBoxDrawn> listTxt = new List<TextBoxDrawn>();
        List<ImageDrawn> listImg = new List<ImageDrawn>();
        bool isCtrl = false;
        public DrawTextInfo()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DrawTextInfo_Loaded);
            // khởi tạo hộp thoại lưu và đọc file cấu hình
            openFileDialog.Title = @"Mở file cấu hình";
            openFileDialog.RestoreDirectory = false;
            openFileDialog.Multiselect = false;

            saveFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(saveFileDialog_FileOk);
            saveFileDialog.Title = @"Lưu file cấu hình";
            saveFileDialog.Filter = "Cmis Data file (*.cdx)|*.cdx";
            saveFileDialog.RestoreDirectory = false;
            //saveFileDialog.Filter = "xdm";

            //BoderCanvas.SizeChanged += new SizeChangedEventHandler(BoderCanvas_SizeChanged); // quản lý kích cỡ parent            
            popupfont.Closed += new EventHandler(pu_Closed); //sự kiện khi đóng Popup            
            popupfont.Opened += new EventHandler(pu_Opened); // sự kiện khi mở Popup  
            popupsite.Closed += new EventHandler(pu_Closed); //sự kiện khi đóng Popup            
            popupsite.Opened += new EventHandler(pu_Opened); // sự kiện khi mở Popup  
            popupsource.Closed += new EventHandler(pu_Closed); //sự kiện khi đóng Popup            
            popupsource.Opened += new EventHandler(pu_Opened); // sự kiện khi mở Popup  
            popUppage.Closed += new EventHandler(pu_Closed); //sự kiện khi đóng Popup            
            popUppage.Opened += new EventHandler(pu_Opened); // sự kiện khi mở Popup  

            //lam menu
            MenuItem mnuItem = new MenuItem();
            mnuItem.Header = "Tạo dữ liệu nguồn";
            mnuItem.Name = "MnuBindingSource";
            mnuItem.Click += new RoutedEventHandler(mnuItem_Click);
            mnu.Items.Add(mnuItem);

            mnuItem = new MenuItem();
            mnuItem.Header = "Thiết lập font";
            mnuItem.Name = "MnuSetFont";
            mnuItem.Click += new RoutedEventHandler(mnuItem_Click);
            mnu.Items.Add(mnuItem);
            // tạo file
            Newfile();
            this.propertyChange += new PropertyChange(PrintPreview_propertyChange);
            this.ToolsPrint.Visibility = Visibility.Collapsed;
            this.PreviewKeyDown += new KeyEventHandler(DrawTextInfo_PreviewKeyDown);
            this.PreviewKeyUp += new KeyEventHandler(DrawTextInfo_KeyUp);
            //test();    
            mainFrame.Focus();
        }

        void DrawTextInfo_KeyUp(object sender, KeyEventArgs e)
        {
            //if (Keyboard.Modifiers == ModifierKeys.Control)
            //{
            isCtrl = false;
            //}
        }

        void DrawTextInfo_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                
                
                if (originalText == null) { return; }
                if (origionalImage == null) { return; }
                TextBoxDrawn txt = originalText as TextBoxDrawn;
                ImageDrawn img = origionalImage as ImageDrawn;
                int _inc = 2;
                bool _shifKey = false;
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    _shifKey = true;
                    isCtrl = true;
                }
                if (e.Key == Key.Left)
                {
                    if (this._originalElement.GetType() == typeof(TextBoxDrawn))
                    {
                        if (listTxt.Count > 0)
                        {
                            foreach (TextBoxDrawn t in listTxt)
                            {
                                if (_shifKey)
                                {
                                    if (txt.Width > 2)
                                    {
                                        t.SetWidth(-_inc);
                                    }
                                }
                                else
                                    t.MoveLeft(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                if (txt.Width > 2)
                                {
                                    txt.SetWidth(-_inc);
                                }
                            }
                            else
                                txt.MoveLeft(_inc);
                        }
                    }
                    else if (this._originalElement.GetType() == typeof(ImageDrawn))
                    {
                        if (listImg.Count > 0)
                        {
                            foreach (ImageDrawn t in listImg)
                            {
                                if (_shifKey)
                                {
                                    if (img.Width > 2)
                                    {
                                        t.SetWidth(-_inc);
                                    }
                                }
                                else
                                    t.MoveLeft(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                if (img.Width > 2)
                                {
                                    img.SetWidth(-_inc);
                                }
                            }
                            else
                                img.MoveLeft(_inc);
                        }
                    }
                    e.Handled = true;
                }
                else if (e.Key == Key.Right)
                {
                    if (this._originalElement.GetType() == typeof(TextBoxDrawn))
                    {
                        if (listTxt.Count > 0)
                        {
                            foreach (TextBoxDrawn t in listTxt)
                            {
                                if (_shifKey)
                                {
                                    t.SetWidth(_inc);
                                }
                                else
                                    t.MoveRight(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                txt.SetWidth(_inc);
                            }
                            else
                                txt.MoveRight(_inc);
                        }
                    }
                    else if (this._originalElement.GetType() == typeof(ImageDrawn))
                    {
                        if (listImg.Count > 0)
                        {
                            foreach (ImageDrawn t in listImg)
                            {
                                if (_shifKey)
                                {
                                    t.SetWidth(_inc);
                                }
                                else
                                    t.MoveRight(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                img.SetWidth(_inc);
                            }
                            else
                                img.MoveRight(_inc);
                        }
                    }
                    e.Handled = true;
                }
                else if (e.Key == Key.Up)
                {
                    if (this._originalElement.GetType() == typeof(TextBoxDrawn))
                    {
                        if (listTxt.Count > 0)
                        {
                            foreach (TextBoxDrawn t in listTxt)
                            {
                                if (_shifKey)
                                {
                                    t.SetHeight(_inc);
                                }
                                else
                                    t.MoveUp(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                txt.SetHeight(_inc);
                            }
                            txt.MoveUp(_inc);
                        }
                    }
                    else if (this._originalElement.GetType() == typeof(ImageDrawn))
                    {
                        if (listImg.Count > 0)
                        {
                            foreach (ImageDrawn t in listImg)
                            {
                                if (_shifKey)
                                {
                                    t.SetHeight(_inc);
                                }
                                else
                                    t.MoveUp(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                img.SetHeight(_inc);
                            }
                            img.MoveUp(_inc);
                        }
                    }
                    e.Handled = true;
                }
                else if (e.Key == Key.Down)
                {
                    if (this._originalElement.GetType() == typeof(TextBoxDrawn))
                    {
                        if (listTxt.Count > 0)
                        {
                            foreach (TextBoxDrawn t in listTxt)
                            {
                                if (_shifKey)
                                {
                                    if (txt.Height > 2)
                                    {
                                        t.SetHeight(-_inc);
                                    }
                                }
                                else
                                    t.MoveDown(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                if (txt.Height > 2)
                                {
                                    txt.SetHeight(-_inc);
                                }
                            }

                            txt.MoveDown(_inc);
                        }
                    }
                    else if (this._originalElement.GetType() == typeof(ImageDrawn))
                    {
                        if (listImg.Count > 0)
                        {
                            foreach (ImageDrawn t in listImg)
                            {
                                if (_shifKey)
                                {
                                    if (txt.Height > 2)
                                    {
                                        t.SetHeight(-_inc);
                                    }
                                }
                                else
                                    t.MoveDown(_inc);
                            }
                        }
                        else
                        {
                            if (_shifKey)
                            {
                                if (txt.Height > 2)
                                {
                                    img.SetHeight(-_inc);
                                }
                            }

                            img.MoveDown(_inc);
                        }
                    }
                    e.Handled = true;
                }
                else if (e.Key == Key.OemPeriod)
                {
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        if (this._originalElement.GetType() == typeof(TextBoxDrawn))
                        {
                            if (listTxt.Count > 0)
                            {
                                foreach (TextBoxDrawn t in listTxt)
                                {
                                    t.Incfont();
                                }
                            }
                            else
                            {
                                txt.Incfont();
                            }
                        }
                    }
                }
                else if (e.Key == Key.OemComma)
                {
                    if (_shifKey)
                    {
                        if (Keyboard.Modifiers == ModifierKeys.Control)
                        {
                            if (listTxt.Count > 0)
                            {
                                foreach (TextBoxDrawn t in listTxt)
                                {
                                    t.Uincfont();
                                }
                            }
                            else
                            {
                                txt.Uincfont();
                            }
                        }
                    }
                }
                else if (e.Key == Key.B)
                {
                    if (Keyboard.Modifiers == ModifierKeys.Shift)
                    {
                        if (Keyboard.Modifiers == ModifierKeys.Control)
                        {
                            if (listTxt.Count > 0)
                            {
                                foreach (TextBoxDrawn t in listTxt)
                                {
                                    t.ToBold();
                                }
                            }
                            else
                            {
                                txt.ToBold();
                            }
                        }
                    }
                }
                else if (e.Key == Key.I)
                {
                    if (Keyboard.Modifiers == ModifierKeys.Shift)
                    {
                        if (Keyboard.Modifiers == ModifierKeys.Control)
                        {
                            if (listTxt.Count > 0)
                            {
                                foreach (TextBoxDrawn t in listTxt)
                                {
                                    t.Uincfont();
                                }
                            }
                            else
                            {
                                txt.ToItalic();
                            }
                        }
                    }
                }
            }
            catch { }
        }

        bool IsPrintPreview = false; // biến quản lý trạng thái print view

        #endregion property and contruction ////////////////////////////////////////////////////////////

        #region Private method

        private void DeleteShape(TextBox e)
        {
            status = STATUS.UPDATE;
            string msg =
            "Bạn thực sự muốn xóa TextBox này?";
            string title = "Delete Shape?";
            MessageBoxButton buttons = MessageBoxButton.YesNo; MessageBoxImage icon = MessageBoxImage.Warning;
            MessageBoxResult result =
            MessageBox.Show(msg, title, buttons, icon);
            if (result == MessageBoxResult.Yes)
                canvas.Children.Remove(e);
            else
            {
                return;
            }
        }

        private void DeleteShape(Image e)
        {
            status = STATUS.UPDATE;
            string msg =
            "Bạn thực sự muốn xóa Image này?";
            string title = "Delete Shape?";
            MessageBoxButton buttons = MessageBoxButton.YesNo; MessageBoxImage icon = MessageBoxImage.Warning;
            MessageBoxResult result =
            MessageBox.Show(msg, title, buttons, icon);
            if (result == MessageBoxResult.Yes)
                canvas.Children.Remove(e);
            else
            {
                return;
            }
        }

        private void AddText(Canvas c, Point pt1, Point pt2)
        {
            status = STATUS.UPDATE;
            TextBoxDrawn txt = new TextBoxDrawn();
            txt.Height = Math.Abs(pt1.Y - pt2.Y); txt.Width = Math.Abs(pt1.X - pt2.X);
            txt.VerticalAlignment = VerticalAlignment.Top;
            txt.HorizontalAlignment = HorizontalAlignment.Left;
            txt.Text = "";
            txt.Focusable = false;
            Canvas.SetTop(txt, pt1.Y);
            Canvas.SetLeft(txt, pt1.X);
            //  txt.Margin = new Thickness(pt1.X, pt1.Y, 0, 0);
            txt.ContextMenu = mnu;
            txt.TextWrapping = TextWrapping.Wrap;
            txt.Text = "";
            txt.IsValue = false;
            originalText = txt;
            c.Children.Add(txt);
            if (baseBrushText == null)
            {
                baseBrushText = txt.BorderBrush;
            }
        }

        private void AddText(Canvas c, double top, double left, double with, double height, string font, double size, string Fonttype, string value, string nameTable, string nameFeild, int _isvalue)
        {
            TextBoxDrawn txt = new TextBoxDrawn();
            txt.Height = height; txt.Width = with;
            txt.VerticalAlignment = VerticalAlignment.Top;
            txt.HorizontalAlignment = HorizontalAlignment.Left;
            txt.ContextMenu = mnu;
            txt.Focusable = false;
            Canvas.SetTop(txt, top);
            Canvas.SetLeft(txt, left);
            //txt.Margin = new Thickness(left,top, 0, 0);
            txt.Text = "";
            originalText = txt;
            c.Children.Add(txt);
            txt.FontFamily = new FontFamily(font);
            txt.FontSize = size;
            txt.TextWrapping = TextWrapping.Wrap;
            if (FontWeights.Bold.ToString() == Fonttype)
            {
                txt.FontWeight = FontWeights.Bold;
            }

            txt._value = value;
            if (value != "" && nameFeild == "")
            {
                txt.Text = value;
            }
            txt.IsValue = _isvalue == 1;

            txt.NameTable = nameTable;
            txt.NameColumn = nameFeild;
            if (baseBrushText == null)
            {
                baseBrushText = txt.BorderBrush;
            }
            // doạn này đéo hiểu kiểu went nó thế nào.
        }
        private void AddImage(Canvas c, double top, double left, double with, double height, string font, double size, string Fonttype, string value, string nameTable, string nameFeild, int _isvalue)
        {
            ImageDrawn img = new ImageDrawn();
            img.Height = height; img.Width = with;
            img.VerticalAlignment = VerticalAlignment.Top;
            img.HorizontalAlignment = HorizontalAlignment.Left;
            img.ContextMenu = mnu;
            img.Focusable = false;
            Canvas.SetTop(img, top);
            Canvas.SetLeft(img, left);
            //txt.Margin = new Thickness(left,top, 0, 0);
            try
            {
                img.Source = new BitmapImage(new Uri(value));
            }
            catch
            {
                ShowErrorMess("Không tìm thấy File ký mẫu C:\\CMIS2Config\\Configs\\PrintLazeContact\\Resign\\Resign.jpg");
                return;
            }
            origionalImage = img;
            c.Children.Add(img);
            img.IsValue = _isvalue == 1;

            // doạn này đéo hiểu kiểu went nó thế nào.
        }

        private void AddImage(Canvas c, Point pt1, Point pt2)
        {
            status = STATUS.UPDATE;
            ImageDrawn img = new ImageDrawn();
            try
            {
                img.Source = new BitmapImage(new Uri("C:\\CMIS2Config\\Configs\\PrintLazeContact\\Resign\\Resign.jpg"));
            }
            catch
            {
                ShowErrorMess("Không tìm thấy File ký mẫu C:\\CMIS2Config\\Configs\\PrintLazeContact\\Resign\\Resign.jpg");
                return;
            }
            img.Height = Math.Abs(pt1.Y - pt2.Y); img.Width = Math.Abs(pt1.X - pt2.X);
            img.VerticalAlignment = VerticalAlignment.Top;
            img.HorizontalAlignment = HorizontalAlignment.Left;
            img._Source = img.Source.ToString();
            img.Focusable = false;
            Canvas.SetTop(img, pt1.Y);
            Canvas.SetLeft(img, pt1.X);
            //  txt.Margin = new Thickness(pt1.X, pt1.Y, 0, 0);
            img.ContextMenu = mnu;
            origionalImage = img;
            c.Children.Add(img);
        }

        private void ShowCurrentPositionOnView(Point p)
        {
            this.lblCurrentPossion.Content = "Current Possion X: " + Math.Round(p.X, 2).ToString() + " Y: " + Math.Round(p.Y, 2).ToString();
        }

        /// <summary>
        /// Tao boder with canvas ở trong
        /// </summary>
        /// <returns></returns>
        private ScrollViewer CreateBoder()
        {
            ScrollViewer br = new ScrollViewer();
            br.ClipToBounds = true;
            br.CanContentScroll = true;
            br.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            br.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            br.Margin = new Thickness(0, 0, 0, 0);
            Canvas c = new Canvas();
            c.VerticalAlignment = VerticalAlignment.Top;
            c.HorizontalAlignment = HorizontalAlignment.Left;
            c.Name = "canvas_" + CANVASCOUNT.ToString();
            c.Height = printInfo.Height;// MiniToPixel;
            c.Width = printInfo.Width;/// MiniToPixel;
            c.MouseMove += new MouseEventHandler(OnMouseMove);
            c.MouseLeftButtonUp += new MouseButtonEventHandler(OnMouseLeftButtonUp);
            c.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseLeftButtonDown);
            br.Content = c;
            borderCurrent = br;
            canvas = c;
            ++CANVASCOUNT;
            return br;
        }

        //tạo một file mới
        private bool Newfile()
        {
            try
            {
                printInfo = new PrintInfo();
                mainFrame.Items.Clear(); // clear các item
                CANVASCOUNT = 0; // trả canvas về 0
                DicImageBackGround.Clear(); ///clear dicImage
                for (int i = 0; i < 1; ++i)
                {
                    mainFrame.Items.Add(GetTabItem());
                }
                CreateHeaderTabItem();
                return true;
            }
            catch
            {
                ShowErrorMess("Tạo file thất bại");
                return false;
            }
        }

        /// <summary>      
        /// Adds the canvas.
        /// Thêm một canvas vào tabItem
        /// </summary>
        /// <param name="item">item cần thêm.</param>
        private TabItem GetTabItem()
        {
            TabItem item = new TabItem();
            item.Content = CreateBoder();
            item.GotFocus += new RoutedEventHandler(tabitem_GotFocus);
            tabItem = item;
            return item;
        }

        //Lấy về canvas hiện tại
        private void GetCurrentCanvas(TabItem sender)
        {
            canvas = ((Canvas)((ScrollViewer)((TabItem)sender).Content).Content);
            borderCurrent = (ScrollViewer)((TabItem)sender).Content;
            //widthParent = ((Border)((TabItem)sender).Content).RenderSize.Width;
            //heightParent = ((Border)((TabItem)sender).Content).RenderSize.Height;            
            if (originalText != null)
            {
                originalText.BorderBrush = baseBrushText;
            }
            originalText = null;
            origionalImage = null;
        }

        //tạo hearderCho các TabItem();
        private void CreateHeaderTabItem()
        {
            for (int i = 0; i < mainFrame.Items.Count; ++i)
            {
                ((TabItem)mainFrame.Items[i]).Header = "Trang" + (i + 1).ToString();
            }
        }

        //insert backGround in dictinary
        private void InsertBackGroundToDic(string key, string value)
        {
            try
            {
                string s = DicImageBackGround[key];
            }
            catch (KeyNotFoundException e)
            {
                DicImageBackGround.Add(key, value);
                return;
            }
            DicImageBackGround[key] = value;
        }
        #region Load file and Save file

        //load dữ liệu từ file XML
        private bool LoadFileConfigData()
        {
            try
            {
                openFileDialog.Filter = "Cmis Data file (*.cdx)|*.cdx";
                openFileDialog.ShowDialog();
                fileName = openFileDialog.FileName;
                if (fileName != "")
                {
                    LoadData(fileName);
                    //LoadData(config);
                }
                return true;
                this.Focus();
            }
            catch (Exception ex)
            {
                ShowErrorMess("File Config có lỗi kiểm tra lại: " + ex.Message);
                return false;
            }
        }

        //load data khi có class
        private void LoadData(string fileName)
        {
            //load data base
            XmlDocument doc = new XmlDocument();
            doc.Load(fileName);
            BaseClassDraw.ConfigPrintLaze config = BaseClassDraw.ConfigPrintLaze.ExportXmlToClass(doc);
            mainFrame.Items.Clear();
            printInfo.Height = config.Height;
            printInfo.Width = config.Width;
            printInfo.TitelPrint = config.Titel;
            printInfo.setTypePint(config.StylePage);
            printInfo.Orientation = config.Orientation;

            foreach (BaseClassDraw.PageInfo _page in config.Pages)
            {
                mainFrame.Items.Add(GetTabItem());
                // tao khoang cac neu _page co current height and current width
                if (_page.HeightCurrentPage != 0 && _page.WidthCurrentPage != 0)
                {
                    canvas.Height = _page.HeightCurrentPage;
                    canvas.Width = _page.WidthCurrentPage;
                }
                //add các text box và add backGround vào canvas
                if (_page.Background != "")
                {
                    SetBackGroundCanvas(canvas, _page.Background);
                }
                foreach (BaseClassDraw.NodeElement node in _page.Nodes)
                {
                    ///add các textbox zo
                    if (node.TypeOfControl == typeof(ImageDrawn).ToString())
                    {
                        AddImage(canvas, node.Y, node.X, node.With, node.Height, node.Font, node.Size, node.StyleFont, node.Value, node.NameTable, node.NameColumn, node.Is_Value);
                        // thiếu đoạn binding ở đây
                    }
                    else
                    {
                        AddText(canvas, node.Y, node.X, node.With, node.Height, node.Font, node.Size, node.StyleFont, node.Value, node.NameTable, node.NameColumn, node.Is_Value);
                    }
                }

            }
            CreateHeaderTabItem();
            Component.Validate.ValidationManager.showMessOnView(this, 2000, "Load file thanh cong", Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
        }

        //SaveData
        private bool SaveData()
        {

            if (fileName == "")
            {
                saveFileDialog.ShowDialog();
            }
            // nếu nó vẫn cù nhầy không nhập thì thoát
            if (fileName == "")
            {
                return false;
            }
            try
            {
                // put data into class Config
                BaseClassDraw.ConfigPrintLaze config = new ConfigPrintLaze();
                config.Height = printInfo.Height;
                config.Width = printInfo.Width;
                config.Titel = printInfo.TitelPrint;
                config.StylePage = printInfo.TypePrintToString();
                config.Orientation = printInfo.Orientation;
                int intpage = 1;
                foreach (TabItem item in mainFrame.Items)
                {
                    //maping data to class page
                    BaseClassDraw.PageInfo _page = new BaseClassDraw.PageInfo();
                    GetCurrentCanvas(item);
                    // neu khoang cach canvas khac thi se set thuoc tinh trong _page luon
                    if (config.Height != canvas.Height && config.Width != canvas.Width)
                    {
                        _page.HeightCurrentPage = canvas.Height;
                        _page.WidthCurrentPage = canvas.Width;
                    }
                    try
                    {
                        string s = DicImageBackGround[canvas.Name];
                        _page.Background = s;
                    }
                    catch (KeyNotFoundException e)
                    {
                        _page.Background = "";
                    }
                    _page.Number = intpage;
                    intpage++;
                    foreach (object o in canvas.Children)
                    {
                        if (o.GetType() == typeof(TextBoxDrawn))
                        {
                            TextBoxDrawn txt = (TextBoxDrawn)o;
                            BaseClassDraw.NodeElement node = new BaseClassDraw.NodeElement();
                            node.StyleFont = txt.FontWeight.ToString();
                            node.Font = txt.FontFamily.ToString();
                            node.Size = txt.FontSize;
                            // node.X = txt.Margin.Left;
                            // node.Y = txt.Margin.Top;
                            node.X = Canvas.GetLeft(txt);
                            node.Y = Canvas.GetTop(txt);
                            node.TypeOfControl = txt.GetType().ToString();

                            node.With = txt.Width;
                            node.Height = txt.Height;
                            node.NameColumn = txt.NameColumn;
                            node.NameTable = txt.NameTable;
                            node.Value = txt._value;
                            node.Is_Value = txt.IsValue ? 1 : 0;
                            //add node vào page
                            _page.Nodes.Add(node);
                        }
                        else if (o.GetType() == typeof(ImageDrawn))
                        {
                            ImageDrawn img = (ImageDrawn)o;
                            BaseClassDraw.NodeElement node = new BaseClassDraw.NodeElement();
                            node.X = Canvas.GetLeft(img);
                            node.Y = Canvas.GetTop(img);
                            node.With = img.Width;
                            node.Height = img.Height;
                            node.Value = ((BitmapImage)img.Source).UriSource.ToString();
                            node.Is_Value = img.IsValue ? 1 : 0;
                            node.TypeOfControl = img.GetType().ToString();
                            //add node vào page
                            _page.Nodes.Add(node);
                        }
                    }
                    //add page
                    config.Pages.Add(_page);
                }
                config.ImportToXmlDoc(fileName);
                Component.Validate.ValidationManager.showMessOnView(this, 2000, "Ghi dữ liệu thành công", Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
                status = STATUS.DONE;
                return true;
            }
            catch (Exception e)
            {
                ShowErrorMess("Ghi dữ liệu có lỗi");
                return false;
            }
        }


        #endregion
        //show infor to print
        private void SetInfoPrint()
        {
            //GetCurrentCanvas(tabItem);
            foreach (TabItem item in mainFrame.Items)
            {
                ScrollViewer scr = item.Content as ScrollViewer;
                Canvas br = (Canvas)scr.Content;
                br.Height = printInfo.Height;
                br.Width = printInfo.Width;
            }
            this.lblInfoPrint.Content = "Kiểu giấy: " + printInfo.TypePrintToString() + ", Cỡ: " + Math.Round(printInfo.Width, 0).ToString() + " x " + Math.Round(printInfo.Height, 0).ToString();
        }

        //show error on view
        private void ShowErrorMess(string str)
        {
            Component.Validate.ValidationManager.showMessOnView(this, 5000, str, Component.Validate.ValidationManager.MESSEGER_TYPE.ERROR_MESSAGE);
        }

        //show Success on view
        private void ShowSussceMess(string str)
        {
            Component.Validate.ValidationManager.showMessOnView(this, 2000, str, Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
        }

        //SetbackGround Canvas
        private void SetBackGroundCanvas(Canvas c, String fileName)
        {
            // Create an ImageBrush.            
            ImageBrush berriesBrush = new ImageBrush();
            berriesBrush.ImageSource =
                new BitmapImage(new Uri(fileName));
            berriesBrush.Stretch = Stretch.Fill;
            //berriesBrush.
            c.Background = berriesBrush;
            InsertBackGroundToDic(c.Name, fileName);
        }

        //setDinding nguồn dữ liệu
        private bool SetBinDing()
        {
            try
            {
                if (originalText != null)
                {
                    sourceDialog = new SetDataSource(popupsource);
                    sourceDialog.setProperty(originalText);
                    sourceDialog.onOkClick += new btnOkClick(sourceDialog_onOkClick);
                    popupsource.Width = sourceDialog.Width;
                    popupsource.Height = sourceDialog.Height;
                    popupsource.Child = new Border { Background = Brushes.LightGray, BorderThickness = new Thickness(1), Child = sourceDialog };
                    popupsource.PlacementTarget = this;
                    popupsource.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
                    popupsource.IsOpen = true;
                    popupsource.Focus();
                    return true;
                }
                else
                {
                    ShowErrorMess("Bạn chưa chọn đối tượng textBox để làm việc");
                    return false;
                }
            }
            catch
            {
                ShowErrorMess("Ko thể set nguồn được đối tượng không phù hợp");
                return false;
            }
        }

        void sourceDialog_onOkClick(object sender)
        {
            ShowSussceMess("Tạo nguồn thành công");
        }

        private void ConfigureMainPage(bool mainPageEnabled, Brush mainPageBackground, bool IsDialogOpened)
        {
            this.IsEnabled = mainPageEnabled;
            this.Background = mainPageBackground;
        }

        #endregion Private Method////////////////////////////////////////////////////////

        #region Event  xử lý giao diện////////////////////////////////////////////////////////////////////////////////
        bool isload = false;
        void DrawTextInfo_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!isload)
                {
                    // SetInfoPrint();
                    cboPrintName.Items.Clear();

                    for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                    {
                        cboPrintName.Items.Add(PrinterSettings.InstalledPrinters[i]);
                    }
                    if (cboPrintName.Items.Count > 0)
                    {
                        cboPrintName.SelectedIndex = 0;
                    }
                    isload = true;
                }
            }
            catch (Exception ex)
            {
                //ShowErrorMess(ex.Message);
            }
        }


        void mnuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mnu = (MenuItem)sender;
            switch (mnu.Name)
            {
                case "MnuBindingSource":
                    SetBinDing();
                    break;
                case "MnuSetFont":
                    btnSetFont_Click(btnSetFont, new RoutedEventArgs());
                    break;
                default:
                    break;
            }
        }

        void tabitem_GotFocus(object sender, RoutedEventArgs e)
        {
            tabItem = (TabItem)sender;
        }

        //Event canvas khi move chuột
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            try
            {

                canvas = (Canvas)sender;
                //show posittion on view
                ShowCurrentPositionOnView(e.GetPosition(canvas));

                //Luôn luôn bắt vị trí đầu tiên của mouse trên canvas
                if (canvas.IsMouseCaptured)
                {
                    currentPoint = e.GetPosition(canvas);
                    if (rubberBand == null)
                    {
                        if (rbtext.IsChecked == true)
                        {
                            rubberBand = new Rectangle(); rubberBand.Stroke = Brushes.LightCoral; rubberBand.StrokeDashArray =
                            new DoubleCollection(new double[] { 4, 2 });
                            canvas.Children.Add(rubberBand);
                        }
                        if (rbimage.IsChecked == true)
                        {
                            rubberBand = new Rectangle(); rubberBand.Stroke = Brushes.LightCoral; rubberBand.StrokeDashArray =
                            new DoubleCollection(new double[] { 4, 2 });
                            canvas.Children.Add(rubberBand);
                        }
                    }
                    //tạo hình vuông

                    if (rbtext.IsChecked == true)
                    {
                        //tạo lề và khoảng cách cho hình vuông
                        double width = Math.Abs(startPoint.X - currentPoint.X);
                        double height = Math.Abs(startPoint.Y - currentPoint.Y);
                        left = Math.Min(startPoint.X, currentPoint.X);
                        top = Math.Min(startPoint.Y, currentPoint.Y);
                        //set lê và khoảng cách, độ rộng và dài
                        rubberBand.Width = width; rubberBand.Height = height;
                        Canvas.SetLeft(rubberBand, left); Canvas.SetTop(rubberBand, top);
                    }
                    if (rbimage.IsChecked == true)
                    {
                        //tạo lề và khoảng cách cho hình vuông
                        double width = Math.Abs(startPoint.X - currentPoint.X);
                        double height = Math.Abs(startPoint.Y - currentPoint.Y);
                        left = Math.Min(startPoint.X, currentPoint.X);
                        top = Math.Min(startPoint.Y, currentPoint.Y);
                        //set lê và khoảng cách, độ rộng và dài
                        rubberBand.Width = width; rubberBand.Height = height;
                        Canvas.SetLeft(rubberBand, left); Canvas.SetTop(rubberBand, top);
                    }
                    if (rbSelect.IsChecked == true)
                    {
                        if (isMovingText)
                        {
                            left = currentPoint.X - leftTextBox;
                            top = currentPoint.Y - topTextBox;
                            if ((_isDragging == false) && ((Math.Abs(e.GetPosition(canvas).X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance) ||
                            (Math.Abs(e.GetPosition(canvas).Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)))
                            {
                                DragStarted();
                            }
                            if (_isDragging)
                            {
                                DragMoved();
                            }
                            // Nhỏ hơn lề thì thoát
                            if (left < leftface || top < topface)
                            {
                                return;
                            }
                            // originalText.Margin = new Thickness(left, top, 0, 0);
                        }
                        if (isMovingImage)
                        {
                            left = currentPoint.X - leftImage;
                            top = currentPoint.Y - topImage;
                            if ((_isDragging == false) && ((Math.Abs(e.GetPosition(canvas).X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance) ||
                            (Math.Abs(e.GetPosition(canvas).Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)))
                            {
                                DragStarted();
                            }
                            if (_isDragging)
                            {
                                DragMoved();
                            }
                            // Nhỏ hơn lề thì thoát
                            if (left < leftface || top < topface)
                            {
                                return;
                            }
                            // originalText.Margin = new Thickness(left, top, 0, 0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowErrorMess(ex.Message);
            }
        }

        //Event canvas khi nhả chuột
        private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                canvas = (Canvas)sender;
                if (rbtext.IsChecked == true) AddText(canvas, startPoint, currentPoint);
                if (rbimage.IsChecked == true) AddImage(canvas, startPoint, currentPoint);
                if (rubberBand != null)
                {
                    canvas.Children.Remove(rubberBand); rubberBand = null;
                }

                if (rbSelect.IsChecked == true)
                {
                    // tao nền adorner cho obj
                    if (isMovingText)
                    {
                        isMovingText = false; //remover adorner 
                        DragFinished(false);
                    }
                    if (isMovingImage)
                    {
                        isMovingImage = false; //remover adorner 
                        DragFinished(false);
                    }
                }
                if (canvas.IsMouseCaptured)
                {
                    canvas.ReleaseMouseCapture();
                }
            }
            catch (Exception ex)
            {
                //ShowErrorMess(ex.Message);
            }
        }

        //Event canvas khi bấm chuột
        private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //if (IsPrintPreview == true)
                //{
                //    return;
                //}
                canvas = (Canvas)sender;
                if (!canvas.IsMouseCaptured)
                {
                    startPoint = e.GetPosition(canvas);
                    canvas.CaptureMouse();
                }
                if (rbSelect.IsChecked == true)
                {
                    if (e.Source is TextBoxDrawn)
                    {
                        // chon nhieu doi tuong
                        if (isCtrl)
                        {
                            if (originalText != null)
                            {
                                if (listTxt.Contains(originalText) == false)
                                    listTxt.Add(originalText);
                            }
                            originalText = (TextBoxDrawn)e.Source;
                            originalText.BorderBrush = Brushes.Red;
                            if (listTxt.Contains(originalText) == false)
                                listTxt.Add(originalText);
                        }
                        else
                        {
                            clearAlltxt();
                            if (originalText != null)
                            {
                                originalText.BorderBrush = baseBrushText;
                            }
                            isMovingText = true;
                            originalText = (TextBoxDrawn)e.Source;
                            _originalElement = (UIElement)originalText;
                            _startPoint = e.GetPosition(canvas);
                            //lấy khoảng cách lề gốc của text với con chuột
                            leftTextBox = startPoint.X - originalText.Margin.Left;
                            topTextBox = startPoint.Y - originalText.Margin.Top;
                            originalText.BorderBrush = Brushes.Red;
                            e.Handled = true;
                            return;
                        }
                    }
                    if (e.Source is ImageDrawn)
                    {
                        // chon nhieu doi tuong
                        if (isCtrl)
                        {
                            if (origionalImage != null)
                            {
                                if (listImg.Contains(origionalImage) == false)
                                    listImg.Add(origionalImage);
                            }
                            origionalImage = (ImageDrawn)e.Source;
                            if (listImg.Contains(origionalImage) == false)
                                listImg.Add(origionalImage);
                        }
                        else
                        {
                            clearAllimg();
                            isMovingImage = true;
                            origionalImage = (ImageDrawn)e.Source;
                            _originalElement = (UIElement)origionalImage;
                            _startPoint = e.GetPosition(canvas);
                            //lấy khoảng cách lề gốc của text với con chuột
                            leftImage = startPoint.X - origionalImage.Margin.Left;
                            topImage = startPoint.Y - origionalImage.Margin.Top;
                            e.Handled = true;
                            return;
                        }
                    }
                }
                else if (rbDelete.IsChecked == true)
                {
                    if (e.Source is TextBoxDrawn)
                    {
                        DeleteShape((TextBoxDrawn)e.Source);
                    }
                    if (e.Source is ImageDrawn)
                    {
                        DeleteShape((ImageDrawn)e.Source);
                    }
                }
            }
            catch (Exception ex)
            {
                //ShowErrorMess(ex.Message);
            }
        }

        private void clearAlltxt()
        {
            foreach (TextBoxDrawn t in listTxt)
            {
                t.BorderBrush = baseBrushText;
            }
            listTxt.Clear();
        }

        private void clearAllimg()
        {
            listImg.Clear();
        }

        private void selectAllTxt()
        {
            listTxt.Clear();
            // lay toan bo txt co tren canvas hien tai cho vao list
            foreach (object i in canvas.Children)
            {
                TextBoxDrawn txt = i as TextBoxDrawn;
                if (txt != null)
                {
                    txt.BorderBrush = Brushes.Red;
                    if (listTxt.Contains(txt) == false)
                        listTxt.Add(txt);
                }
            }
        }

        private void selectAllImg()
        {
            listImg.Clear();
            // lay toan bo txt co tren canvas hien tai cho vao list
            foreach (object i in canvas.Children)
            {
                ImageDrawn img = i as ImageDrawn;
                if (img != null)
                {
                    if (listImg.Contains(img) == false)
                        listImg.Add(img);
                }
            }
        }

        private void btnChonHet_Click(object sender, RoutedEventArgs e)
        {
            selectAllTxt();
        }

        private Point _startPoint;
        private bool _isDragging;
        private double _originalLeft;
        private double _originalTop;
        private UIElement _originalElement;
        private SimpleCircleAdorner _overlayElement;

        private void DragStarted()
        {
            _isDragging = true;
            _originalLeft = Canvas.GetLeft(_originalElement);
            _originalTop = Canvas.GetTop(_originalElement);

            _overlayElement = new SimpleCircleAdorner(_originalElement);
            double _dbheight = _overlayElement.Height;
            double _dbwidth = _overlayElement.Width;
            AdornerLayer layer = AdornerLayer.GetAdornerLayer(_originalElement);
            layer.Add(_overlayElement);
        }

        private void DragMoved()
        {
            Point CurrentPosition = System.Windows.Input.Mouse.GetPosition(canvas);

            _overlayElement.LeftOffset = CurrentPosition.X - _startPoint.X;
            _overlayElement.TopOffset = CurrentPosition.Y - _startPoint.Y;

        }

        private void DragFinished(bool cancelled)
        {
            System.Windows.Input.Mouse.Capture(null);
            if (_isDragging)
            {
                AdornerLayer.GetAdornerLayer(_overlayElement.AdornedElement).Remove(_overlayElement);

                if (cancelled == false)
                {
                    Canvas.SetTop(_originalElement, _originalTop + _overlayElement.TopOffset);
                    Canvas.SetLeft(_originalElement, _originalLeft + _overlayElement.LeftOffset);
                }
                _overlayElement = null;
            }
            _isDragging = false;
        }

        #endregion end event //////////////////////////////////

        #region Evnet Xử lý thao tác người dùng

        //setBackGround
        private void btnSetPicture_Click(object sender, RoutedEventArgs e)
        {
            status = STATUS.UPDATE;
            try
            {
                openFileDialog.Filter = "Image files (*.jpg)|*.jpg|(*.bmp)|*.bmp";
                openFileDialog.ShowDialog();
                if (openFileDialog.FileName != "")
                {
                    SetBackGroundCanvas(canvas, openFileDialog.FileName);
                    openFileDialog.FileName = "";
                }
            }
            catch
            {
                ShowErrorMess("Không tồn tại file ảnh này hoặc không đúng định dạng");
            }
        }

        //setFont
        private void btnSetFont_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                status = STATUS.UPDATE;
                if (canvas.IsMouseCaptured)
                {
                    canvas.ReleaseMouseCapture();
                }
                if (originalText != null)
                {
                    if (fontdialog == null)
                    {
                        fontdialog = new FontDialog.FontChooser(popupfont);
                        fontdialog.SetPropertiesFromObject(originalText);
                        if (listTxt != null)
                        {
                            fontdialog._ListDependencyObject = listTxt;
                        }
                        popupfont.Width = fontdialog.Width;
                        popupfont.Height = fontdialog.Height;
                        popupfont.Child = new Border { Background = Brushes.LightGray, BorderThickness = new Thickness(1), Child = fontdialog };
                        popupfont.PlacementTarget = this;
                        popupfont.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
                    }
                    popupfont.IsOpen = true;
                    popupfont.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        void saveFileDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
        {
            fileName = saveFileDialog.FileName;
            if (fileName != "")
            {
                saveFileDialog.FileName = "";
            }
            else
            {
                ShowErrorMess("Không thể lưu được nếu bạn ko nhập tên");
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (status != STATUS.DONE)
                {
                    MessageBoxResult result = MessageBox.Show("Bạn có muốn lưu bản ghi này trước khi mở file mới? ", "Thong bao", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                        if (!SaveData())
                            return;
                }
                LoadFileConfigData();
                //SetInfoPrint();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        void pu_Closed(object sender, EventArgs e)
        {
            this.ConfigureMainPage(true, null, false);

        }

        void pu_Opened(object sender, EventArgs e)
        {
            this.ConfigureMainPage(
                false,
                new BrushConverter().ConvertFromString("#8F8F8F") as SolidColorBrush,
                true);
        }

        private void btnNewPage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                status = STATUS.UPDATE;
                mainFrame.Items.Add(GetTabItem());
                CreateHeaderTabItem();
                tabItem.Focus();
                ShowSussceMess("Thêm Page thành công");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        private void btnDeletePage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                status = STATUS.UPDATE;
                MessageBoxResult result = MessageBox.Show("Bạn có chắc muốn xóa trang này không? ", "Thong bao", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    status = STATUS.UPDATE;
                    int index = mainFrame.Items.IndexOf(tabItem);
                    mainFrame.Items.Remove(tabItem);
                    ShowSussceMess("Xóa Page thành công");
                    if (mainFrame.SelectedItem is TabItem)
                    {
                        CreateHeaderTabItem();
                        ((TabItem)mainFrame.SelectedItem).Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        private void btnPageSize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                status = STATUS.UPDATE;
                if (canvas.IsMouseCaptured)
                {
                    canvas.ReleaseMouseCapture();
                }
                ConfigPrint dialog = new ConfigPrint(popUppage);
                dialog.onOpenClick += new OpenClick(dialog_onOpenClick);
                dialog.SetProperty(printInfo);
                popUppage.Width = dialog.Width;
                popUppage.Height = dialog.Height;
                popUppage.Child = new Border { Background = Brushes.LightGray, BorderThickness = new Thickness(1), Child = dialog };
                popUppage.PlacementTarget = this;
                popUppage.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
                popUppage.IsOpen = true;
                popUppage.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        void dialog_onOpenClick(object sender, PrintInfo e, bool is_Current)
        {
            if (is_Current)
            {
                //lay ve selection cua tabControl 
                int index = mainFrame.SelectedIndex;
                ScrollViewer br = (ScrollViewer)((TabItem)mainFrame.Items[index]).Content;
                Canvas c = (Canvas)br.Content;
                c.Height = e.Height;
                c.Width = e.Width;
                return;
            }
            SetInfoPrint();
        }

        private void btnNewFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (status != STATUS.DONE)
                {
                    MessageBoxResult result = MessageBox.Show("Bạn có muốn lưu bản ghi này trước khi tạo mới ko? ", "Thong bao", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        if (!SaveData())
                        {
                            return;
                        }

                    }
                }
                Newfile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        private void btnBindingClick(object sender, RoutedEventArgs e)
        {
            try
            {
                SetBinDing();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }

        // trinh cỡ
        private void btnSiteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                MakeSiteText dialog = new MakeSiteText(popupsite);
                dialog.Txt = originalText;
                popupsite.Width = dialog.Width;
                popupsite.Height = dialog.Height;
                popupsite.Child = new Border { Background = Brushes.White, BorderThickness = new Thickness(1), Child = dialog };
                popupsite.PlacementTarget = this;
                popupsite.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
                popupsite.IsOpen = true;
                popupsite.Focus();
                //w.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thong bao");
            }
        }


        #endregion

        #region Process with print

        int _currentPage = 1;
        event PropertyChange propertyChange;
        public int CurrentPage
        {
            get
            {
                return _currentPage;
            }
            set
            {
                _currentPage = value;
                if (propertyChange != null)
                    propertyChange(CurrentPage);
            }
        }

        /// <summary>
        /// Event Xem trước kết quả in
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>        
        private void btnPrinPreview_Click(object sender, RoutedEventArgs e)
        {
            PrintPReview();
        }

        public void setSource(System.Data.DataTable tb, string strfileName)
        {
            try
            {
                _tblSource = tb;
                fileName = strfileName;
                LoadData(strfileName); // load dữ liệu luôn nè

                PrintPReview();

                rbSelect.IsChecked = true;

                //BtnNewFile.Visibility = Visibility.Collapsed;
                BtnDeletePage.Visibility = Visibility.Collapsed;
                //BtnNewPage.Visibility = Visibility.Collapsed;
                //BtnPageSize.Visibility = Visibility.Collapsed;
                //BtnOpen.Visibility = Visibility.Collapsed;
                //btnPriPreview.Visibility = Visibility.Collapsed;

                //rbDelete.Visibility = Visibility.Collapsed;
                //rbSite.Visibility = Visibility.Collapsed;
                //rbSelect.Visibility = Visibility.Collapsed;
                //rbtext.Visibility = Visibility.Collapsed;
                btnBinDing.Visibility = Visibility.Collapsed;
                btnSetPicture.Visibility = Visibility.Collapsed;
                //btnSetFont.Visibility = Visibility.Collapsed;
                MakeOpitonTrangIn();
            }
            catch (Exception ex)
            {
                ShowErrorMess(ex.Message);
            }
        }

        private void BtnNavigate_click(object sender, RoutedEventArgs e)
        {
            Button bt = (Button)sender;
            switch (bt.Name)
            {
                case "btnBack":
                    CurrentPage--;
                    break;
                case "btnBackEnd":
                    CurrentPage = 1;
                    break;
                case "btnNext":
                    CurrentPage++;
                    break;
                case "btnNextEnd":
                    CurrentPage = _tblSource.Rows.Count;
                    break;
                default:
                    break;
            }
        }

        //event khi thay đổi current Page
        void PrintPreview_propertyChange(object pro)
        {
            try
            {
                int i = (Int32)pro;
                /// nếu i =0 Enable false Back, back end
                if (i == 1)
                {
                    this.btnBack.IsEnabled = false;
                    this.btnBackEnd.IsEnabled = false;
                    this.btnNext.IsEnabled = true;
                    this.btnNextEnd.IsEnabled = true;
                }
                else if (i == _tblSource.Rows.Count)
                {
                    this.btnNext.IsEnabled = false;
                    this.btnNextEnd.IsEnabled = false;
                    this.btnBack.IsEnabled = true;
                    this.btnBackEnd.IsEnabled = true;
                }
                else
                {
                    this.btnNext.IsEnabled = true;
                    this.btnNextEnd.IsEnabled = true;
                    this.btnBack.IsEnabled = true;
                    this.btnBackEnd.IsEnabled = true;
                }
                if (i == _tblSource.Rows.Count)
                {
                    this.btnNext.IsEnabled = false;
                    this.btnNextEnd.IsEnabled = false;
                }
                this.lblcurentPage.Content = "Trang " + i.ToString() + @"/" + (_tblSource.Rows.Count).ToString();
                //maping dữ liệu
                MapObject(i - 1);
            }
            catch (Exception ex)
            {
                ShowErrorMess(ex.Message);
            }
        }

        // map object với nguồn
        public bool MapObject(int intPage)
        {
            if (_tblSource == null)
                return false;
            if (intPage >= _tblSource.Rows.Count)
                return false;

            foreach (TabItem item in mainFrame.Items)
                //get Border
                if (item.Content is ScrollViewer)
                    if (((ScrollViewer)item.Content).Content is Canvas)
                    {
                        canvas = (Canvas)((ScrollViewer)item.Content).Content;
                        //lấy được canvas map các đối tượng text box với nguồn
                        foreach (object t in canvas.Children)
                        {
                            if (t.GetType() == typeof(TextBoxDrawn))
                            {
                                TextBoxDrawn txt = (TextBoxDrawn)t;
                                // tìm theo nguồn dữ liệu                            
                                string _ng = txt.NameColumn;
                                txt.Text = "";
                                if (txt.IsValue == true)
                                {
                                    if (txt._value != "")
                                    {
                                        txt.Text = txt._value;
                                    }
                                    continue;
                                }
                                try
                                {
                                    if (intPage == -1)
                                    {
                                        txt.Text = "";
                                    }
                                    else if (intPage >= 0)
                                    {
                                        object obj = _tblSource.Rows[intPage][_ng.Trim()];
                                        if (obj != null)
                                        {
                                            txt.Text = obj.ToString();
                                        }
                                    }//else if(txt.ta
                                }

                                catch (ArgumentException ex)
                                {
                                }
                            }
                        }
                    }
            return true;
        }

        private void btnPrint_click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cboPrintName.Text == "")
                {
                    ShowErrorMess("Đề nghị chọn máy in");
                    return;
                }
                print(txtSourcePrint.Text);

            }
            catch (Exception ex)
            {
                ShowErrorMess(ex.Message);
            }
        }

        PrintDocument prtDoc = new PrintDocument();

        public string PageIn = "ALL";

        public void print(string strSq)
        {

            prtDoc.PrinterSettings.PrinterName = cboPrintName.Text;

            if (printInfo.Orientation == "LANDSCAPE")
            {
                prtDoc.DefaultPageSettings.Landscape = true;
            }
            else
            {
                prtDoc.DefaultPageSettings.Landscape = false;
            }
            prtDoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
            prtDoc.OriginAtMargins = true;
            prtDoc.PrintPage += new PrintPageEventHandler(prtDoc_PrintPage);
            System.Windows.Forms.PrintPreviewDialog printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();

            int countPrint = 1;
            int.TryParse(txtSourcePrint.Text, out countPrint);
            if (countPrint == 0)
                countPrint++; // defaut 1
            try
            {
                for (int i = 0; i < countPrint; ++i)
                {
                    for (int j = 0; j < _tblSource.Rows.Count; ++j)
                    {
                        procesPrint(j, PageIn);
                    }
                }
            }
            catch
            {
                ShowErrorMess("Chỉ lệnh in nhập vào không chuẩn xác đề nghị kiểm tra lại");
            }


        }

        private bool procesPrint(int page, string TItemPrint)
        {
            try
            {
                MapObject(page);
                for (int i = 0; i < mainFrame.Items.Count; ++i)
                {
                    bool isPrint = true;
                    if (TItemPrint != "ALL")
                    {
                        if (TItemPrint != (i + 1).ToString())
                        {
                            isPrint = false;
                        }
                    }
                    if (isPrint)
                    {
                        canvas = (Canvas)((ScrollViewer)(((TabItem)mainFrame.Items[i]).Content)).Content;
                        System.Diagnostics.Debug.WriteLine(page);
                        prtDoc.Print();
                    }
                }
                return true;
            }
            catch
            {
                ShowErrorMess("Không kết nối được máy in đề nghị chọn máy in chính xác");
                return false;
            }
        }

        void prtDoc_PrintPage(object sender, PrintPageEventArgs e)
        {

            try
            {
                foreach (object obj in canvas.Children)
                {
                    if (obj.GetType() == typeof(TextBoxDrawn))
                    {
                        TextBox txtBox1 = (TextBox)obj;
                        System.Drawing.Font fnt;
                        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Convert.ToInt32(Canvas.GetLeft(txtBox1)), Convert.ToInt32(Canvas.GetTop(txtBox1)), Convert.ToInt32(txtBox1.Width), Convert.ToInt32(txtBox1.Height));
                        //e.Graphics.DrawRectangle(Pens.Blue, rect);
                        if (txtBox1.FontWeight.ToString() == "Bold")
                        {
                            fnt = new System.Drawing.Font(txtBox1.FontFamily.ToString(), (float)txtBox1.FontSize, System.Drawing.FontStyle.Bold);
                        }
                        else if (txtBox1.FontWeight.ToString() == "Italic")
                        {
                            fnt = new System.Drawing.Font(txtBox1.FontFamily.ToString(), (float)txtBox1.FontSize, System.Drawing.FontStyle.Italic);
                        }
                        else
                        {
                            fnt = new System.Drawing.Font(txtBox1.FontFamily.ToString(), (float)txtBox1.FontSize);
                        }
                        //double tam = Canvas.GetLeft(txtBox1);007 50802  018 40102
                        e.Graphics.DrawString(txtBox1.Text, fnt, System.Drawing.Brushes.Black, rect);
                    }
                    else if (obj.GetType() == typeof(ImageDrawn))
                    {
                        ImageDrawn image1 = (ImageDrawn)obj;
                        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Convert.ToInt32(Canvas.GetLeft(image1)), Convert.ToInt32(Canvas.GetTop(image1)), Convert.ToInt32(image1.Width), Convert.ToInt32(image1.Height));
                        BitmapImage bitmapImage = (BitmapImage)image1.Source;
                        System.Drawing.Bitmap bitmap = null;
                        var width = bitmapImage.PixelWidth;
                        var height = bitmapImage.PixelHeight;
                        var stride = width *((bitmapImage.Format.BitsPerPixel + 7) / 8);
                        var bits = new byte[height * stride];
                        bitmapImage.CopyPixels(bits, stride, 0);
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        System.Windows.Media.Imaging.BmpBitmapEncoder bbe = new BmpBitmapEncoder();
                        bbe.Frames.Add(BitmapFrame.Create(new Uri(image1.Source.ToString(), UriKind.RelativeOrAbsolute)));
                        bbe.Save(ms);
                        System.Drawing.Image img2 = System.Drawing.Image.FromStream(ms); 
                        //bitmap = new System.Drawing.Bitmap(width, height, stride,
                        //                                    System.Drawing.Imaging.PixelFormat.Format32bppArgb,
                        //                                    ptr);
                        //e.Graphics.DrawImage(System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap()), (float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height);
                        e.Graphics.DrawImage(img2, (float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height);
                    }
                }
            }
            catch
            {
            }

        }

        public void PrintPReview()
        {
            if (_tblSource == null)
            {
                throw new Exception("chưa có nguồn dữ liệu đề nghị thiết lập");
                return;
            }
            if (_tblSource.Rows.Count == 0)
            {
                throw new Exception("chưa có nguồn dữ liệu đề nghị thiết lập");
            }
            if (canvas.IsMouseCaptured)
            {
                canvas.ReleaseMouseCapture();
            }
            IsPrintPreview = true;
            //ToolsBox.Visibility = Visibility.Collapsed;
            //ToolMangerFile.Visibility = Visibility.Collapsed;
            MainToolBarTop.HorizontalAlignment = HorizontalAlignment.Center;
            ToolsPrint.Visibility = Visibility.Visible;
            CurrentPage = 1;
        }

        // tạo các option trang in
        public void MakeOpitonTrangIn()
        {
            if (mainFrame.Items.Count > 1)
            {
                RadioButton rdo = new RadioButton();
                rdo.Content = "ALL";
                rdo.Margin = new Thickness(2, 2, 2, 2);
                rdo.Checked += new RoutedEventHandler(rdo_Checked);
                rdo.IsChecked = true;
                WtuyChon.Children.Add(rdo);
                for (int i = 1; i < mainFrame.Items.Count + 1; ++i)
                {
                    RadioButton r = new RadioButton();
                    r.Content = i.ToString();
                    r.Margin = new Thickness(2, 2, 2, 2);
                    r.Checked += new RoutedEventHandler(rdo_Checked);
                    r.IsChecked = false;
                    WtuyChon.Children.Add(r);
                }
            }
        }

        void rdo_Checked(object sender, RoutedEventArgs e)
        {
            PageIn = ((RadioButton)sender).Content.ToString();
        }

        #endregion

    }
    //delegete khi CurrentPage Change
    public delegate void PropertyChange(object pro);
}
